<template>
	<view class="tree-node-item">
		<view @click="handleClick" class="select-item" style="display: flex; justify-content: space-between; padding-right: 30rpx; align-items: center; margin: 15rpx 0;">
			<view style="display: flex; align-items: center; justify-content: space-between;">
				<text v-if="node.children && node.children.length > 0">{{ node.open ? '▲' : '▼' }}</text>
				<text>{{ node[props.props.label] || node.label }}</text>
			</view>
			<view>
				<view style="display: flex; align-items: center; justify-content: end; gap: 20rpx;">
					<up-button size="mini" type="primary" @click="handleAdd">新建子标签</up-button>
					<up-button size="mini" type="primary" plain @click="handleEdit">编辑</up-button>
					<up-button size="mini" type="error" @click="handleDelete">删除</up-button>
				</view>
			</view>
		</view>
		<view v-if="node.open && node.children && node.children.length > 0">
			<tree-node v-for="(child, index) in node.children" :props="props.props" :key="index" :node="child" @handleAdd="handleChildrenAdd" @handleEdit="handleChildrenEdit" @handleDelete="handleChildrenDelete"
				@toggle="$emit('toggle', child)"></tree-node>
		</view>
	</view>
</template>

<script setup>
	import {
		defineProps,
		defineEmits
	} from 'vue';

	const props = defineProps({
		node: {
			type: Object,
			required: true
		},
		props: {
			type: Object,
			default: () => ({})
		}
	});

	const emit = defineEmits(['toggle', 'handleAdd', 'handleEdit', 'handleDelete']);

	const handleClick = () => {
		if (props.node.children && props.node.children.length > 0) {
			emit('toggle', props.node);
		}
	};
	
	const handleAdd = (e) => {
		emit('handleAdd', props.node)
	}
	
	const handleChildrenAdd = (node) => {
		emit('handleAdd', node)
	}
	
	const handleChildrenEdit = (node) => {
		emit('handleEdit', node)
	}
	
	const handleChildrenDelete = (node) => {
		emit('handleDelete', node)
	}
	
	const handleEdit = (e) => {
		emit('handleEdit', props.node)
	}
	
	const handleDelete = (e) => {
		emit('handleDelete', props.node)
	}
</script>

<style scoped>
	.tree-node-item {
		padding-left: 20px;
	}
	
	.select-item {
		height: 60rpx;
	}
	
	.select-item:hover {
		background-color: white;
	}
</style>